package com.ja.openchat.ui.chat.redpacket;

import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.RadioButton;

import androidx.lifecycle.ViewModelProviders;

import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.JsonObject;
import com.ja.openchat.AppViewModelFactory;
import com.ja.openchat.BR;
import com.ja.openchat.R;
import com.ja.openchat.databinding.ActivityPostRedPacketBinding;
import com.ja.openchat.ui.me.SetPayPwdFragment;
import com.ja.openchat.viewmodels.PostRedViewModel;
import com.ja.openchat.views.DigitTextWatcher;
import com.ja.openchat.views.SimpleTextWatcher;
import com.ja.openchat.views.VerificationCodeView;
import com.ja.openchat.views.VerifyPayPasswordDialog;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnCancelListener;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.zy.openchat.Constants;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgResponse;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.message.ChatInfo;
import com.zy.openchat.core.model.redpacket.RedPacketInfo;
import com.zy.openchat.core.model.wallet.WalletInfo;

import java.util.Map;

import me.goldze.mvvmhabit.base.BaseActivity;

public class PostRedPacketActivity extends BaseActivity<ActivityPostRedPacketBinding, PostRedViewModel> {

    public static void startActivity(Context context, ChatInfo chatInfo){
        Intent intent = new Intent(context,PostRedPacketActivity.class);
        intent.putExtra("conversation", chatInfo);
        context.startActivity(intent);
    }

    private ChatInfo chatInfo;

    private int preCheckedId = -1;

    //0：普通红包  1：拼手气红包
    private int currentRedType = 0;

    private boolean isGroupChat = false;

    public boolean isNormalType(){
        return currentRedType == 0;
    }

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_post_red_packet;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }


    @Override
    public PostRedViewModel initViewModel() {
        //使用自定义的ViewModelFactory来创建ViewModel，如果不重写该方法，则默认会调用LoginViewModel(@NonNull Application application)构造方法
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getApplication());
        return ViewModelProviders.of(this, factory).get(PostRedViewModel.class);
    }

    @Override
    public void initView() {
        super.initView();
        binding.toolbar.toolbar.setBackgroundResource(R.drawable.shape_bg_color);
        binding.toolbar.tvBarTitle.setText("发红包");
        if(getIntent()!=null){
            chatInfo = getIntent().getParcelableExtra("conversation");
        }
        binding.toolbar.ivBarBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        binding.submitBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                submit();
            }
        });
        binding.redGroup.setOnCheckedChangeListener((group, checkedId) -> {
            if(preCheckedId>0&&group.findViewById(checkedId)!=null){
                RadioButton radioButton = (RadioButton)group.findViewById(preCheckedId);
                radioButton.setTypeface(Typeface.DEFAULT);
                radioButton.setTextSize(15);
            }
            RadioButton radioButton1 = group.findViewById(checkedId);
            radioButton1.setTypeface(Typeface.DEFAULT_BOLD);
            radioButton1.setTextSize(17);
            preCheckedId = checkedId;
            currentRedType = checkedId==R.id.raido1?1:0;
            binding.redAmountLable.setText(isNormalType()?"单个金额":"总金额");
        });
        binding.redNumEt.addTextChangedListener(new SimpleTextWatcher(){
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                checkBtn();
            }
        });
        new DigitTextWatcher(binding.redAmountEt){
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                super.onTextChanged(s, start, before, count);
                checkBtn();
            }
        };
        if(chatInfo!=null){
            isGroupChat = chatInfo.isGroup();
            if(isGroupChat){
                binding.redNumLayout.setVisibility(View.VISIBLE);
                binding.redGroup.check(R.id.raido1);
                binding.redGroup.setVisibility(View.VISIBLE);
            }else{
                binding.redGroup.setVisibility(View.GONE);
                binding.redNumLayout.setVisibility(View.GONE);
            }
        }
    }

    private void checkBtn(){
        if(isGroupChat){
            binding.submitBtn.setEnabled(!TextUtils.isEmpty(binding.redNumEt.getText().toString())&&!TextUtils.isEmpty(binding.redAmountEt.getText().toString()));
        }else{
            binding.submitBtn.setEnabled(!TextUtils.isEmpty(binding.redAmountEt.getText().toString()));
        }
    }

    private void submit(){
        if(chatInfo==null){
            ToastUtils.showShort("信息获取错误");
            return;
        }
        float price = Float.parseFloat(binding.redAmountEt.getText().toString());
        if(price<=0){
            ToastUtils.showShort(!isNormalType()?"请输入红包总金额":"请输入红包单个金额");
            return;
        }
        int number = isGroupChat?Integer.parseInt(binding.redNumEt.getText().toString()):1;
        if(!isNormalType()&&(price/number<0.01f)){
            ToastUtils.showShort("红包总金额过小，不能发红包");
            return;
        }
        String desStr = TextUtils.isEmpty(binding.redRemarkEt.getText().toString())? Constants.DEFAULT_RED_PACKET_TITLE :binding.redRemarkEt.getText().toString();
        RedPacketInfo info = new RedPacketInfo();
        info.chatId = isGroupChat?ChatInfo.toServerPeerId(chatInfo.id):chatInfo.id;
        info.title = desStr;
        info.count = number;
        //1.单聊红包 2.拼手气红包 3.普通红包
        if(isGroupChat){
            if(!isNormalType())
            {//手气红包
                info.type = 2;
                info.price = price/number;
                info.total_price = price;
            } else {//普通红包
                info.type = 3;
                info.price = price;
                info.total_price = price*info.count;
            }
        }else{
            info.type = 1;
            info.price = price;
            info.total_price = price*info.count;
        }

        showProgress();
        TelegramManager.getTelegramManager().queryWalletInfo(this, new TgResultBlock<WalletInfo>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, WalletInfo walletInfo) {
                hideProgress();
                if(walletInfo!=null){
                    if(!walletInfo.hasPaymentPassword) {
                        tipSetWalletPaymentPasswordDialog();
                    } else {
                        if(walletInfo.balance<info.total_price) {//余额不足
                            ToastUtils.showShort("钱包余额不足，请前往余额中心充值");
                        } else {
                            //输入支付密码
                            PostRedPacketActivity.this.showPasswordDialog(info);
                        }
                    }
                }else{
                    ToastUtils.showShort("请求错误，请稍后重试");
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                ToastUtils.showShort("请求超时，请稍后重试");
            }
        });
    }

    //设置支付密码
    private void tipSetWalletPaymentPasswordDialog(){
        new XPopup.Builder(PostRedPacketActivity.this).autoDismiss(true).asConfirm("提示", "尚未设置支付密码，现在去设置？", "取消", "设置", new OnConfirmListener() {
            @Override
            public void onConfirm() {
                startContainerActivity(SetPayPwdFragment.class.getCanonicalName());
//                startActivity(new Intent(PostRedPacketActivity.this, SetPayPasswordActivity.class));
//                SetPayPasswordActivity.start(PostRedPacketActivity.this, false);
            }
        }, new OnCancelListener() {
            @Override
            public void onCancel() {

            }
        },false).show();

    }

    //输入支付密码
    private void showPasswordDialog(RedPacketInfo info){
        if(info==null){
            return;
        }
        new XPopup.Builder(this)
                .autoOpenSoftInput(true)
                .asCustom(new VerifyPayPasswordDialog(this,String.format("%.2f",info.total_price), new VerificationCodeView.OnInputFinishListener() {
                    @Override
                    public void onInputFinish(String text) {
                        info.password = text;
                        sumitPasswork(info);
                    }
                }))
                .show();
    }

    public void sumitPasswork(RedPacketInfo info){
        if(info==null){
            return;
        }
        showProgress();
        TelegramManager.getTelegramManager().createRp(this, info, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                hideProgress();
                if(obj!=null){
                    if(obj.ok){
                        finish();
                    }else if(400 == obj.errCode){
                        //todo wangyutao
                            ToastUtils.showShort("钱包余额不足，请千万余额中心充值");
                    }
                    else if(401 == obj.errCode)
                    {
                        ToastUtils.showShort("红包个数最多1000个");
                    }
                    else if(402 == obj.errCode)
                    {
                        ToastUtils.showShort("单个红包金额不能小于0.01元");
                    }
                    else if(403 == obj.errCode)
                    {
                        ToastUtils.showShort("单个红包金额不能大于10000元");
                    }
                    else if(404 == obj.errCode)
                    {
                        new XPopup.Builder(PostRedPacketActivity.this).autoDismiss(true).asConfirm("提示", "支付密码错误，重新输入？", "取消", "确定", new OnConfirmListener() {
                            @Override
                            public void onConfirm() {
                                showPasswordDialog(info);
                            }
                        }, new OnCancelListener() {
                            @Override
                            public void onCancel() {

                            }
                        },false).show();
                    }else if(501 == obj.errCode){
                        ToastUtils.showShort("对方把你加入了黑名单，不能发红包");
                    }
                    else
                    {
                        ToastUtils.showShort("红包创建失败，请稍后再试");
                    }
                }else{

                }

            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                ToastUtils.showShort("请求超时，请稍后重试");
            }
        });
    }


}
